package com.zhengdongzulin.zuke.app.main.mine.lifeservice

import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.Gson
import com.luck.picture.lib.entity.LocalMedia
import com.lxj.androidktx.core.*
import com.xuexiang.xui.widget.picker.widget.TimePickerView
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder
import com.xuexiang.xui.widget.picker.widget.configure.TimePickerType
import com.zhengdongzulin.zuke.R
import com.zhengdongzulin.zuke.app.data.ChangeHomeData
import com.zhengdongzulin.zuke.app.data.Imgs
import com.zhengdongzulin.zuke.app.data.LifeServiceDetails
import com.zhengdongzulin.zuke.base.*
import com.zhengdongzulin.zuke.databinding.ZkActivityLifeServiceCreateBinding
import com.zhengdongzulin.zuke.ext.*
import com.zhengdongzulin.zuke.utils.DateFormatConstants
import com.zhengdongzulin.zuke.utils.DateUtils
import java.io.File
import java.lang.StringBuilder
import java.text.SimpleDateFormat
import java.util.*


class ZKLifeServiceCreateActivity :
    BaseActivity<LifeServiceCreateVm, ZkActivityLifeServiceCreateBinding>() {

    lateinit var mHouseId: String
    lateinit var mType: String  //保洁    维修    投诉
    lateinit var mData: LifeServiceDetails

    var mResult: MutableList<LocalMedia> = mutableListOf()
    var mImages: MutableList<Imgs> = mutableListOf()
    lateinit var mAdapter: ItemAdapter
    var mTimePicker: TimePickerView? = null
    var mCount = 0
    var mImgs: StringBuilder = StringBuilder()

    override fun getLayoutResId(): Int = R.layout.zk_activity_life_service_create

    override fun initVM(): LifeServiceCreateVm = getVM(LifeServiceCreateVm::class.java)

    override fun initView() {
        isInitDialog = true
        mType = intent.getStringExtra("type")!!
        mHouseId =
            Gson().fromJson(sp().getString("change_home", ""), ChangeHomeData::class.java).houseId
        when (mType) {
            "保洁", "维修" -> {
                setTitleContent("预约$mType")
                mView.tvLifeServiceCreateDesc.text = "请简要说明您的${mType}要求"
                mView.llLifeServiceCreateTime.visibility = View.VISIBLE
            }
            "投诉" -> {
                setTitleContent("我要投诉")
                mView.tvLifeServiceCreateDesc.text = "申请原因"
                mView.llLifeServiceCreateTime.visibility = View.GONE
            }
        }


        val calendar: Calendar = Calendar.getInstance()
        calendar.setTime(DateUtils.millis2Date(System.currentTimeMillis()))
        mTimePicker = TimePickerBuilder(
            this
        ) { date, v ->
            mView.tvLifeServiceCreateTime.text =
                DateUtils.date2String(date, SimpleDateFormat(DateFormatConstants.yyyyMMddHHmm))
        }
            .setTimeSelectChangeListener { }
            .setType(TimePickerType.DATE)
            .setCancelColor(color(R.color.color_1273f7))
            .setSubmitColor(color(R.color.color_1273f7))
            .setTitleColor(color(R.color.color_1273f7))
            .setDividerColor(color(R.color.color_1273f7))
            .setTextColorCenter(color(R.color.color_1273f7))
            .setTitleText("时间选择")
            .setOutSideCancelable(false)
            .setDate(calendar)
            .build()
    }

    override fun initData() {
        mImages?.add(Imgs("", true))
        mAdapter = ItemAdapter(mImages!!)
        mAdapter.animationEnable = true
        mAdapter.addChildClickViewIds(R.id.img, R.id.remove)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.img) {
                if (mImages!![position].isEmpty) {
                    openGallery(mResult!!) { isSuccess, result ->
                        if (isSuccess && result != null && result.size > 0) {
                            mImages?.clear()
                            mResult?.clear()
                            mResult!!.addAll(result!!)
                            for (localMedia in result) {
                                mImages!!.add(Imgs(localMedia.getFilePath()))
                            }
                            if (mImages!!.size < 5) {
                                mImages!!.add(Imgs("", true))
                            }
                            mAdapter.notifyDataSetChanged()
                        }
                    }
                } else {

                }
            } else if (view.id == R.id.remove) {
                mImages!!.removeAt(position)
                mResult!!.removeAt(position)
                if (mResult!!.size == 4) {
                    mImages!!.add(Imgs("", true))
                }
                for (i in position..(mImages!!.size)) {//局部刷新避免闪烁问题
                    mAdapter.notifyItemChanged(i)
                }
            }

        }
        mView.recyclerView.vertical(4).adapter = mAdapter
    }


    override fun initListener() {
        mView.btnLifeServiceCreateCommit.setOnClickListener {
            commit()
        }
        mView.tvLifeServiceCreateTime.setOnClickListener {
            mTimePicker?.show()
        }
        mView.btnLifeServiceCreateTime.setOnClickListener {
            mTimePicker?.show()
        }
    }

    override fun startObserve() {
        mViewModel.clean_apply.observe(this, androidx.lifecycle.Observer {
            getDialog("保洁预约成功", "您已预约成功，保洁会按照约定时间上门服务") {
                //通知上个页面刷新列表
                finish()
            }.show()
        })
        mViewModel.clean_apply.state.observe(this, getObserver(mViewModel.clean_apply))

        mViewModel.repair_apply.observe(this, androidx.lifecycle.Observer {
            getDialog("维修预约成功", "您已预约成功，维修会按照约定时间上门服务") {
                //通知上个页面刷新列表
                finish()
            }.show()
        })
        mViewModel.repair_apply.state.observe(this, getObserver(mViewModel.repair_apply))

        mViewModel.complaint_letter_apply.observe(this, androidx.lifecycle.Observer {
            getDialog("投诉成功", "已收到您的投诉信息，我们会尽快核实您的投诉并处理，很抱歉给您造成的不便，请谅解。") {
                //通知上个页面刷新列表
                finish()
            }.show()
        })
        mViewModel.complaint_letter_apply.state.observe(
            this,
            getObserver(mViewModel.complaint_letter_apply)
        )

        //上传图片
        mViewModel.upload.observe(this, androidx.lifecycle.Observer {
            mCount++
            mImgs.append("${it[0].url},")
            if (mCount == mImages.size - 1) {
                commit1()
            }
        })
        mViewModel.upload.state.observe(this, getObserver(mViewModel.upload))
    }

    data class FileData(var url: String, var name: String)

    private fun commit() {
        var time = mView.tvLifeServiceCreateTime.getTextZ()
        var content = mView.etLifeServiceCreateInput.getTextZ()

        if (mType != "投诉" && time == "请选择") {
            toast("请选择时间")
            return
        }

        if (content.isNullOrEmpty()) {
            toast("请输入内容")
            return
        }


        if (mImages.size > 1) {
            //处理图片 并且上传
            for (mImage in mImages) {
                if (!mImage.isEmpty) {
                    mViewModel.upload(File(mImage.src))
                }
            }
        } else {
            commit1()
        }

    }

    private fun commit1() {
        var time = mView.tvLifeServiceCreateTime.getTextZ()
        var content = mView.etLifeServiceCreateInput.getTextZ()
        var mImgsStr = ""
        if (!mImgs.isNullOrEmpty()) {
            mImgsStr = mImgs.toString().substring(0, mImgs.toString().length - 1)
        }
        when (mType) {
            "保洁" -> {
                mViewModel.clean_apply(mHouseId, time, content, mImgsStr)
            }
            "维修" -> {
                mViewModel.repair_apply(mHouseId, time, content, mImgsStr)
            }
            "投诉" -> {
                mViewModel.complaint_letter_apply(mHouseId, content, mImgsStr)
            }
        }
    }

    inner class ItemAdapter(
        list: MutableList<Imgs>
    ) : BaseQuickAdapter<Imgs, BaseViewHolder>(
        R.layout.item_feedback,
        list
    ) {
        override fun convert(holder: BaseViewHolder, item: Imgs) {
            if (item.isEmpty) {
                holder.setVisible(R.id.remove, false)
                holder.loadImage(R.id.img, R.mipmap.add_img_empty, 0, 2.0f)
            } else {
                holder.setVisible(R.id.remove, true)
                holder.loadImage(R.id.img, item.src, 0, 2.0f)
            }

        }
    }

}